package com.pacific.sign.common.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

    private static final String MD_ALGORITHM = "MD5";

    public static MessageDigest getMessageDigestInstance() {
        try {
            return MessageDigest.getInstance(MD_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static char hexNibble(int n) {
        if (n < 10) {
            return (char) (n + '0');
        } else {
            return (char) (n - 10 + 'a');
        }
    }

    public static String stringDigest(byte [] d) {
        byte [] hash = digest(d);
        char buf[] = new char[32];
        for (int i=0, j=0; i<hash.length; i++) {
            int x = hash[i] & 255;
            buf[j++] = hexNibble(x >> 4);
            buf[j++] = hexNibble(x & 15);
        }
        return new String(buf);
    }

    public static String stringDigest(String s) {
        return stringDigest(s.getBytes());
    }

    public static String stringDecimalDigest( String s ) {
        String hexDigest = stringDigest( s );
        BigInteger bi = new BigInteger( hexDigest, 16 );
        return bi.toString();
    }

    public static byte [] digest(byte [] d) {
        MessageDigest md = getMessageDigestInstance();
        return md.digest(d);
    }

    public static byte [] digest(String s) {
        return  digest(s.getBytes());
    }
}
